<script setup>
import { ref } from 'vue'
import { RedirectAPI } from '@/api/LoginRedirect.js'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.js'
const userStore = useUserStore()
const router = useRouter()

const formcs = ref(null) //表单DOM元素
// 输入内容
const form = ref({
  username: '',
  password: '',
  passwords: ''
})

const Redirect = async () => {
  // 注册成功之前，先进行校验，校验成功 → 请求，检验失败 → 自动提示
  await formcs.value.validate()
  const res = await RedirectAPI(form.value)
  userStore.setToken(res.token) // 调用pinia的自定义方法，将token存入pinia中
  ElMessage.success('注册成功,进入登录界面')
  router.push('/home')
  // 用延时函数解决注册登录后名字显示不出的bug
  setTimeout(() => {
    router.go(0)// 模拟刷新
  }, 100);
}


// 校验
const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 10, message: '密码必须是 5-10位 的字符', trigger: 'blur' }
  ],
  passwords: [
    // 自定义校验
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback() // 就算校验成功，也需要 callback()
        }
      },
      trigger: 'blur'
    }
  ],
}
</script>

<template>
  <div class="parent">
    <div class="box">
      <h1>用户注册</h1>
      <el-form label-width="55px" autocomplete="off" :model="form" :rules="rules" ref="formcs">
        <el-form-item label="用户名">
          <el-input class="username" placeholder="请输入用户名" v-model="form.username" />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input class="password" type="password" placeholder="请输入密码" show-password
            v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item prop="passwords" label="重复">
          <el-input class="password" type="password" placeholder="请重复输入密码" show-password
            v-model="form.passwords"></el-input>
        </el-form-item>
        <div class="container">
          <el-button size="large" type="success" class="button" @click="Redirect">注册</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.parent {
  width: 100%;
  height: 90vh;
  display: grid;
  grid-template-columns: repeat(11, 1fr);
  grid-template-rows: repeat(7, 1fr);
  grid-column-gap: 0px;
  grid-row-gap: 0px;
}

.box {
  grid-area: 1 / 4 / 5 / 9;
  padding: 20px;

  .username,
  .password {
    height: 40px;
    padding: 0 10px;
  }

  h1 {
    text-align: center;
    padding: 22px 0 22px 20px;
  }

  .container {
    display: flex;
    justify-content: center;

    .button {
      width: 50%;
      background: #5bbe9e;
    }
  }
}
</style>
